<template>
  <el-dialog v-model="showDialog"
             :title="title"
             :destroy-on-close="true"
             :close-on-click-modal="false"
             :draggable="true"
             @open="openDialog"
             @opened="initDialog"
             @close="closeDialog(userInfoRef)"
             @closed="closedDialog">
    <el-form :model="userInfoDetail"
             :rules="userInfoRules"
             ref="userInfoRef"
             :disabled="(dialogType === DIALOG_VIEW)"
             label-suffix=":"
             label-width="100px"
             status-icon>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userInfoDetail.username"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="userInfoDetail.sex">
              <template v-for="item in sexData">
                <el-radio :label="item.value">{{ item.label }}</el-radio>
              </template>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="userInfoDetail.phone"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userInfoDetail.email"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="省份" prop="province">
            <el-select v-model="userInfoDetail.province"
                       :clearable="true"
                       :filterable="true"
                       @blur="blurProvince"
                       @change="changeProvince"
            >
              <el-option v-for="item in provinceData" :value="item.value" :label="item.label"
                         :key="item.key || item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="地市" prop="city">
            <el-select v-model="userInfoDetail.city"
                       :clearable="true"
                       :filterable="true"
                       @blur="blurCity"
                       @change="changeCity"
            >
              <el-option v-for="item in cityData" :value="item.value" :label="item.label"
                         :key="item.key || item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="区域" prop="area">
            <el-select v-model="userInfoDetail.area"
                       :clearable="true"
                       :filterable="true"
            >
              <el-option v-for="item in areaData" :value="item.value" :label="item.label"
                         :key="item.key || item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="userInfoDetail.address" type="textarea"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="个人简介" prop="description">
            <el-input v-model="userInfoDetail.description" type="textarea"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer v-if="DIALOG_ADD == dialogType || DIALOG_EDIT == dialogType">
      <el-button type="primary" @click="saveFn(userInfoRef)" :loading="saveLoading">保存</el-button>
      <el-button type="default" @click="closeDialog(userInfoRef)">取消</el-button>
    </template>
    <template #footer v-else>
      <el-button type="danger" @click="closeDialog(userInfoRef)">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {DIALOG_VIEW, DIALOG_EDIT, DIALOG_ADD} from '@/constants/common-constant.ts'
import {reactive, ref, watch} from "vue";
import {saveUserInfoReq} from '@/api/admin/user.ts'
import {elMessageTip, warningMessageTip} from "@/utils/tip-utils.ts";
import {RESPONSE_CODE_SUCCESS} from "@/config/common-config.ts";
import {type FormInstance, type FormRules} from "element-plus";
import {areaDataUtil, dictDataUtil} from "@/utils/common-request.ts";
import {SYSTEM_SEX} from "@/constants/dict-constants.ts";
import {checkIsNull} from "@/utils/check-utils.ts";

const props = defineProps(
    {
      showDialog: {
        type: Boolean,
        default: false
      },
      title: {
        type: String,
        default: '用户详情'
      },
      dialogType: {
        type: String,
        default: DIALOG_VIEW
      },
      detailParam: {
        type: Object,
        default: () => {
        }
      }
    })

const emits = defineEmits(['openDialog', 'initDialog', 'closeDialog', 'closedDialog'])

interface UserInfoDetail {
  id: string;
  username: string;
  phone: string;
  email: string;
  sex: string
  province: string;
  city: string;
  area: string;
  address: string;
  description: string;
}

const userInfoDetail = reactive<UserInfoDetail>({
  id: '',
  username: '',
  phone: '',
  email: '',
  sex: '2',
  province: '',
  city: '',
  area: '',
  address: '',
  description: ''
})

const userInfoRef = ref<FormInstance>();

const userInfoRules = reactive<FormRules<UserInfoDetail>>({
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
  ],
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
  ]
})

const sexData = ref<any>(() => [])

const provinceData = ref<any>(() => [])

const cityData = ref<any>(() => [])

const areaData = ref<any>(() => [])

const saveLoading = ref<boolean>(false);

const initSexData = async () => {
  sexData.value = await dictDataUtil(SYSTEM_SEX);
}

const initProvinceInfo = async () => {
  provinceData.value = await areaDataUtil('0', '');
}

const initCityInfo = async (parentCode: string) => {
  cityData.value = await areaDataUtil(parentCode, '');
}

const initAreaInfo = async (parentCode: string) => {
  areaData.value = await areaDataUtil(parentCode, '');
}

const showDialog = ref(props.showDialog)

watch(() => props.showDialog, val => {
  showDialog.value = val
})

const openDialog = () => {
  emits('openDialog')
}

const initDialog = () => {
  emits('initDialog')
  initSexData().then();
  initProvinceInfo().then();
  if (props.dialogType === DIALOG_VIEW || props.dialogType === DIALOG_EDIT) {
    initUserInfo();
    blurProvince().then()
    blurCity().then()
  }
}

const closeDialog = (formEl: FormInstance | undefined) => {
  emits('closeDialog', false)
  resetForm(formEl)
}

const closedDialog = () => {
  emits('closedDialog', {showDialog: false, dialogType: props.dialogType})
}

const saveFn = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (!valid) {
      warningMessageTip('请填写完整信息')
      return;
    }
  })

  saveLoading.value = true
  const params = {
    id: props.detailParam.id,
    username: userInfoDetail.username,
    phone: userInfoDetail.phone,
    email: userInfoDetail.email,
    sex: userInfoDetail.sex,
    province: userInfoDetail.province,
    city: userInfoDetail.city,
    area: userInfoDetail.area,
    address: userInfoDetail.address,
    description: userInfoDetail.description
  }
  const res: any = await saveUserInfoReq(params);
  saveLoading.value = false
  elMessageTip(res.tipType, res.message)
  if (res.code === RESPONSE_CODE_SUCCESS) {
    closedDialog()
  }
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const initUserInfo = () => {
  userInfoDetail.id = props.detailParam.id
  userInfoDetail.username = props.detailParam.username
  userInfoDetail.sex = props.detailParam.sex.toString();
  userInfoDetail.phone = props.detailParam.phone
  userInfoDetail.email = props.detailParam.email
  userInfoDetail.province = props.detailParam.province
  userInfoDetail.city = props.detailParam.city
  userInfoDetail.area = props.detailParam.area
  userInfoDetail.address = props.detailParam.address
  userInfoDetail.description = props.detailParam.description
}

const blurProvince = async () => {
  const currentProvince = userInfoDetail.province;

  if (checkIsNull(currentProvince)) {
    userInfoDetail.city = ''
    cityData.value = []
    userInfoDetail.area = ''
    areaData.value = []
  } else {
    await initCityInfo(currentProvince)
  }
}

const blurCity = async () => {
  const currentCity = userInfoDetail.city
  if (checkIsNull(currentCity)) {
    userInfoDetail.area = ''
    areaData.value = []
  } else {
    await initAreaInfo(currentCity)
  }
}

const changeProvince = async (value: any) => {
  userInfoDetail.city = ''
  cityData.value = []
  userInfoDetail.area = ''
  areaData.value = []
  if (!checkIsNull(value)) {
    await initCityInfo(value)
  }
}

const changeCity = async (value: any) => {
  userInfoDetail.area = ''
  areaData.value = []
  if (!checkIsNull(value)) {
    await initCityInfo(value)
  }
}


</script>

<style scoped>

</style>